from fastapi import APIRouter, Depends
from app.schemas.detection import ResultGroupOut, ResultGroupDetailOut, DetectionGroupCreate
from app.utils.oss_service import upload_detection_image
from app.crud.crud_detection import get_result_groups_by_user, get_result_group_detail, create_result_group_with_items, get_result_group_by_user_and_title
from app.database.session import get_db
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List
from fastapi import HTTPException
from app.models.models import ResultGroup, ResultItem

router = APIRouter(tags=["检测结果存储服务"])

@router.get("/detection/groups/", response_model=List[ResultGroupOut])
async def get_groups(user_id: int, db: AsyncSession = Depends(get_db)):
    groups = await get_result_groups_by_user(db, user_id)
    return [ResultGroupOut(id=g.id, title=g.title) for g in groups]

@router.get("/detection/group/{group_id}", response_model=ResultGroupDetailOut)
async def get_group_detail(group_id: int, db: AsyncSession = Depends(get_db)):
    group = await get_result_group_detail(db, group_id)
    if not group:
        raise HTTPException(status_code=404, detail="分组不存在")
    items = [
        {
            "id": item.id,
            "oss_url": item.oss_url,
            "detection_info": item.detection_info,
            "created_at": item.created_at.isoformat()
        }
        for item in group.items
    ]
    return {"id": group.id, "title": group.title, "items": items}

@router.post("/detection/group/", response_model=ResultGroupOut)
async def create_group_with_items(data: DetectionGroupCreate, db: AsyncSession = Depends(get_db)):
    # 查找同用户同名分组
    group = await get_result_group_by_user_and_title(db, data.user_id, data.title)
    if not group:
        group = ResultGroup(user_id=data.user_id, title=data.title)
        db.add(group)
        await db.flush()  # 获取group.id
    # 先上传所有图片到OSS并插入检测项
    for item in data.items:
        oss_url = await upload_detection_image(item.image_base64)
        db_item = ResultItem(group_id=group.id, oss_url=oss_url, detection_info=item.detection_info)
        db.add(db_item)
    await db.commit()
    await db.refresh(group)
    return ResultGroupOut(id=group.id, title=group.title) 